package com.siyoumi.app.sys.admin;

import com.siyoumi.app.entity.SysItem;
import com.siyoumi.app.sys.entity.EnumRedirectType;
import com.siyoumi.app.sys.service.CommonApiServcie;
import com.siyoumi.app.sys.vo.CommonItemData;
import com.siyoumi.app.sys.vo.VaSysItem;
import com.siyoumi.app.service.SysItemService;
import com.siyoumi.component.XApp;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.config.SysConfig;
import com.siyoumi.controller.AdminApiController;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.util.*;
import com.siyoumi.validator.XValidator;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/xadmin/sys/api")
public class ApiAdmin
        extends AdminApiController {
    @PostMapping({"/upload_file"})
    public XReturn uploadFile(@RequestParam("file0") MultipartFile file0) {
        List<String> ex = List.of("mp4", "pdf");
        return CommonApiServcie.getBean().uploadFile(file0, ex, SysConfig.getIns().getUploadFileSizeMax(), null);
    }

    @PostMapping({"/upload_img"})
    public XReturn uploadImg(@RequestParam("file0") MultipartFile file0) {
        List<String> ex = XFile.getImgExtenstions();
        return CommonApiServcie.getBean().uploadFile(file0, ex, SysConfig.getIns().getUploadFileSizeMax(), null);
    }

    @GetMapping({"/item__list"})
    public XReturn itemList() {
        String idSrc = input("id_src");
        if (XStr.isNullOrEmpty(idSrc)) {
            return EnumSys.MISS_VAL.getR("miss id_src");
        }

        setPageTitle("项编辑");
        List<CommonItemData> list = new ArrayList<>();

        SysItem entityItem = SysItemService.getBean().getEntityByIdSrc(idSrc);
        if (entityItem != null) {
            list = entityItem.commonData();
        }

        getR().setData("list", list);
        //跳转方式
        setPageInfo("enum_redirect_type", IEnum.toMap(EnumRedirectType.class));

        return getR();
    }

    @PostMapping({"/item__edit"})
    public XReturn itemEdit(@Validated VaSysItem entity, BindingResult result) {
        //统一验证
        XValidator.getResult(result);
        //
        SysItemService app = SysItemService.getBean();

        InputData inputData = XHttpContext.InputAll();

        SysItem entityItem = app.getEntityByIdSrc(entity.getItem_id_src());
        if (entityItem != null) {
            inputData.put("id", entityItem.getKey());
        }
        //
        List<String> ignoreField = new ArrayList<>();
        if (isAdminEdit()) {
            //过滤字段
            ignoreField.add("item_id_src");
        }

        return XApp.getTransaction().execute(status -> app.saveEntity(inputData, entity, true, ignoreField));
    }
}
